package com.ji.client;

import com.ji.protocol.JCProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Title:
 * Description:
 * Author:吉
 * Since:2017/5/19
 * Version:1.1.0
 */
public class EchoClientHandler extends ChannelInboundHandlerAdapter {

    private final String msg = "hello java world";

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // Send the message to Server
        JCProtocol protocol=new JCProtocol(msg);
        ctx.writeAndFlush(protocol);
        System.out.println(msg);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
//        ByteBuf buf = (ByteBuf) msg;
//        byte[] req = new byte[buf.readableBytes()];
//        buf.readBytes(req);
//        try {
//            String body = new String(req, "UTF-8");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        System.out.println(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // Close the connection when an exception is raised.
        ctx.close();
    }
}
